package com.fbs.framework.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.fbs.framework.exception.TokenException;
import io.micrometer.common.util.StringUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/*
创建者:虾米糖
*/
@Slf4j
public class GlobalInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        request.setAttribute("请求开始时间startTime",System.currentTimeMillis());
        log.info("请求开始【URI:{},Method:{},Params:{}】",request.getRequestURI(),request.getMethod(), JSONObject.toJSON(request.getParameterMap()));
        String token = request.getHeader("token");
        log.info("token:{}",token);
        if(StringUtils.isEmpty(token)){
            throw new TokenException();
        }


        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("postHandle");
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("afterCompletion");
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
